﻿using UnityEngine;

namespace ZCUtil.Singleton
{
    public abstract class Singleton<T> where T : new()
    {
        static object _lock = new object();
        private static T _instance;

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                        }
                    }
                }
                return _instance;
            }
        }

        public virtual void Release()
        {
            _instance = default(T);
        }
    }

    public class SingletonMono<T> : MonoBehaviour where T : Component
    {
        private static bool _isApplicationQuit = false;
        private static T _instance;

        public bool IsLive
        {
            get
            {
                if (_instance == null)
                {
                    return false;
                }
                return !_isApplicationQuit;
            }
        }

        public static T Instance
        {
            get
            {
                if (_instance == null && !_isApplicationQuit)
                {
                    _instance = FindObjectOfType(typeof(T)) as T;
                    if (_instance == null)
                    {
                        GameObject obj = new GameObject();
                        obj.name = typeof(T).Name.ToString();
                        _instance = (T)obj.AddComponent(typeof(T));
                    }
                    if (Application.isPlaying)
                    {
                        GameObject.DontDestroyOnLoad(_instance);
                    }
                }
                return _instance;
            }
        }

        protected virtual void OnApplicationQuit()
        {
            _isApplicationQuit = true;
        }

        protected virtual void OnDestory()
        {
            _isApplicationQuit = true;
            _instance = null;
        }
    }
}